<?php

namespace App\Http\Controllers\Admin;

use App\ComboRefundLog;
use App\Member;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;


class RefundOrderController extends Controller
{
    public function index(Request $request){
        //dd(111);
        return view('admin.refundOrder.list');
    }
    public function ajax_list(Request $request){
        $model= ComboRefundLog::with('member');
        $model=$model->orderBy('id','desc')->paginate($request->limit)
            ->toArray();

        foreach ($model['data'] as $k=>$v){
           $member= Member::where('id',$v['member_id'])->first();
           if($member){
               $parent= Member::where('id',$member->pid)->first();
               if($parent){
                   $model['data'][$k]['parent']=$parent;
               }else{
                   $model['data'][$k]['parent']=[];
               }
           }
        }
        //dd($model);
        return $this->page_json_render($model);
    }
    public function report(Request $request){
        $cellData = [
            [
                'id',
                '套餐',
                '用户',
                '推广人',
                '推还金额',
                '发放时间',

            ]
        ];

        $model= ComboRefundLog::with('member');
        if(isset($request->searchTime)&&$request->searchTime!=''){
            $timeArray=explode('~',$request->searchTime);
            $start_time=trim($timeArray[0]);
            $end_time=trim($timeArray[1]);

            $model=$model->whereBetween('created_at',[$start_time,$end_time]);
        }
        $model=$model->get()->toArray();

        foreach ($model as $k=>$v){
            $member= Member::where('id',$v['member_id'])->first();
            if($member){
                $parent= Member::where('id',$member->pid)->first();
                if($parent){
                    $parent_name=$parent->nickname;
                }else{
                    $parent_name='暂无推广人';
                }
            }
            $temp_data = [
                $v['id'],
                $v['combo_name'],
                preg_replace('/[\xf0-\xf7].{3}/',' ',isset($v['member']['nickname'])?$v['member']['nickname']:'匿名用户'),
                preg_replace('/[\xf0-\xf7].{3}/',' ',$parent_name),
                $v['refund_money'],
                $v['created_at']
            ];
            $cellData[] = $temp_data;
        }
        Excel::create('退款订单',function($excel) use ($cellData){
            $excel->sheet('orders', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');
    }
}
